package com.ruibo.tax.service.impl;

import com.ruibo.modules.utils.SendDataUtil;
import com.ruibo.tax.constants.TaxConstants;
import com.ruibo.tax.model.HBJHHBCF;
import com.ruibo.tax.model.HBJHJCZDJC;
import com.ruibo.tax.repository.HBJHJCZDJCRepository;
import com.ruibo.tax.service.HBJHJCZDJCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: a
 * @author: 孙 峰
 * @time: 2020/10/15 15:24
 */
@Slf4j
@Service
public class HBJHJCZDJCServiceImpl implements HBJHJCZDJCService {
    @Autowired
    private HBJHJCZDJCRepository hbjhjczdjcRepository;
    @Autowired
    private SendDataUtil sendDataUtil;

    @Override
    public List<HBJHJCZDJC> findByStatusAndSendStatus(String status, String sendStatus, Pageable pageable) {
        Page<HBJHJCZDJC> hbjhjczdjcPage = hbjhjczdjcRepository.findByStatusAndSendStatus(status, sendStatus, pageable);
        List<HBJHJCZDJC> collect = hbjhjczdjcPage.get().collect(Collectors.toList());
        return collect;
    }

    @Override
    @Transactional
    public void updateReceiptStatusByUUID(String send, String uuid) {
        hbjhjczdjcRepository.updateReceiptStatusByUUID(send, uuid);
    }

    @Override
    public void processingUnsentHZData() {
        int unSendCount = hbjhjczdjcRepository.countAllByReceiptStatusAndSendStatusAndTimesLessThan(null, TaxConstants.SEND, 3);
        // 发送数据
        int pages = (int) Math.ceil(unSendCount / 50.0);

        for (int i = 0; i < pages; i++) {
            Sort sort = Sort.by(Sort.Direction.ASC, "id");
            PageRequest request = PageRequest.of(0, 50, sort);
            Page<HBJHJCZDJC> hbjhhbcfPage = hbjhjczdjcRepository.findAllByReceiptStatusAndSendStatusAndTimesLessThan(null, 3, TaxConstants.SEND, request);

            List<HBJHJCZDJC> list = hbjhhbcfPage
                    .stream()
                    .collect(Collectors.toList());
            sendDataUtil.sendZDJCDataToMQ(list);
            // 执行完压缩之后
            list.forEach(hbjhjczdjc -> {
                //修改数据发送次数
                hbjhjczdjc.setTimes(hbjhjczdjc.getTimes() == null ? 1 : hbjhjczdjc.getTimes() + 1);
            });
            hbjhjczdjcRepository.saveAll(list);
            log.info("执行本次数据包发送成功");
        }
    }
}
